import re
from datetime import datetime
from datetime import timedelta
from django_redis import get_redis_connection
from rest_framework import serializers
from django.contrib.auth import get_user_model
from ten.settings import REGEX_MOBILE

User = get_user_model()


class SmsSerializer(serializers.Serializer):
    mobile = serializers.CharField(max_length=11)
    def validate_mobile(self, mobile):
        """
        验证手机号码
        :param data:
        :return:
        """
        # 手机是否注册
        if User.objects.filter(mobile=mobile).count():
            raise serializers.ValidationError("用户已经存在")
        # 验证手机号码是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码非法")
        # 验证码发送频率
        one_mintes_ago = datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
        # 链接redis数据库
        redis_conn = get_redis_connection('verify_code')
        send_count = redis_conn.get('send_count_%s' % mobile)

        if send_count.objects.filter(add_time__gt=one_mintes_ago, mobile=mobile).count():
            raise serializers.ValidationError("距离上一次发送未超过60s")
        return mobile

class RegisterSerializer(serializers.ModelSerializer):
    '''
    注册
    '''
    # 添加token字段
    token = serializers.CharField(label='JWT Token', read_only=True)

    class Meta:
        model = User
        # 需要在fields中，声明相关序列化器的字段
        fields = ('id', 'username', 'mobile', 'token','avatar','password')
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        # 保存用户数据并对密码加密
        user = User.objects.create_user(**validated_data)
        return user

